﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Paging;
using SDT.Site.ViewModels;
using SDT.Site.Properties;
using System.Threading;
using System.Globalization;
using SDT.Lib.Common;

namespace SDT.Site.Controllers
{
    public class QuestionController : Controller
    {
        SDTDataContext eDataContext = new SDTDataContext();

        public QuestionController()
        {
            var currentCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
        }

        //
        // GET: /Question/

        public ActionResult Index(int? id, int? page)
        {
            page = page.HasValue && page.Value > 0 ? page.Value : 1;
            string order = "ID desc";
            IPagedList<Question> que = eDataContext.Questions
                                      .Where(p => p.PubYN == true)
                                      .Where(p=>id!=null && id.Value>0? p.CatID==id.Value:true)
                                      .OrderBy(string.Format("{0}", order))
                                      .ToPagedList(page.Value - 1, Settings.Default.ProductPageSize);
            var q = new QuestionViewModels();
            q.Questions = que;
            q.Category = id.HasValue && id.Value > 0 ? eDataContext.QuestionCategories.Where(e => e.ID == id.Value).SingleOrDefault() : null;
           
            return View(q);
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 19/07/2011
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult Lasted(int catid, string title)
        {
            string order = "nViews desc";
            List<Question> Que = eDataContext.Questions
                          .Where(c => c.PubYN == true)
                          .Where(c=>catid>0? c.CatID==catid: true)
                          .OrderBy(string.Format("{0}", order))
                          .ToPagedList(Settings.Default.IntDefault, Settings.Default.nItemRightSite).ToList();
            ViewData["Title"] = title;
            return View(Que);
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 19/07/2011
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult Newsest(int catid, string title)
        {
            string order = "AddDate desc";
            List<Question> pro = eDataContext.Questions
                          .Where(c => c.PubYN == true)
                          .Where(c => catid > 0 ? c.CatID == catid : true)
                          .OrderBy(string.Format("{0}", order))
                          .ToPagedList(Settings.Default.IntDefault, Settings.Default.nItemRightSite).ToList();
            ViewData["Title"] = title;
            return View(pro);
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 20/07/2011
        /// </summary>
        /// <returns></returns>
        [Authorize()]
        public ActionResult Create()
        {
            QuestionInputModels q = new QuestionInputModels();
            q.QuestionCategory = eDataContext.QuestionCategories.Where(c => c.ActiveYN == true).OrderBy(e=>e.Priority).ToList();
           
            return View(q);
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 20/07/2011
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [ValidateInput(false)]
        public ActionResult Create(QuestionInputModels m)
        {
            try
            {
                if (Request["CaptchaText"].ToLower() == HttpContext.Session["captchastring"].ToString().ToLower())
                {
                    var u = UserManager.GetUser(UserManager.GetUserId(), true);
                    UpdateModel(m.Question);
                    m.Question.CatID = Utils.ParseInt(Request["ddlCategory"]) > 0 ? Utils.ParseInt(Request["ddlCategory"]) : (int?)null;
                    m.Question.AddDate = DateTime.Now;
                    m.Question.SendBy = u.UserName;
                    m.Question.SendEmail = u.Email;
                    m.Question.AddBy = UserManager.GetUserId();
                    eDataContext.Questions.InsertOnSubmit(m.Question);
                    eDataContext.SubmitChanges();
                    return View("Success");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.ERR_CAPTCHA_VALIDATE;
                    m.QuestionCategory = eDataContext.QuestionCategories.Where(c => c.ActiveYN == true).ToList();
                    return View(m);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog(ex);
                return View("Fail");
            }
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 20/07/2011
        /// </summary>
        /// <returns></returns>
        public ActionResult Details(int id, int? page)
        {
            Question que = eDataContext.Questions.Where(q => q.ID == id).FirstOrDefault();

            string order = "AddDate desc";
            page = page.HasValue ? page.Value : 1;
            IPagedList<Answer> listA = eDataContext.Answers
                                .Where(a => a.QuestionID == id && a.PubYN.HasValue && a.PubYN.Value == true)
                                .OrderBy(string.Format("{0}", order))
                                .ToPagedList(page.Value - 1, Settings.Default.AnswerPageSize);

            // increment nViews
            que.nViews = que.nViews + 1;
            eDataContext.SubmitChanges();

            return View(new QuestionInputModels()
            {
                Question = que,
                ListAnswer = listA
            });
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 21/07/2011
        /// </summary>
        [ValidateInput(false)]
        public ActionResult Answer(QuestionInputModels m)
        {
            UpdateModel(m);
            m.Answer.AddDate = DateTime.Now;
            m.Answer.PubYN = false;

            // increment nAnswers
            Question q = eDataContext.Questions.Where(qu => qu.ID == m.Answer.QuestionID).FirstOrDefault();
            q.nAnswers = q.nAnswers + 1;

            // insert answer
            eDataContext.Answers.InsertOnSubmit(m.Answer);
            eDataContext.SubmitChanges();

            return RedirectToAction("Index");
        }
    }
}
